﻿using Microsoft.EntityFrameworkCore;
using MiniErp.Model.Entities;
using MiniErp.Mysql.Data;
using MiniErp.Repository.IRepository;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace MiniErp.Repository.Repository
{
    public class UsetInfoRepository : IUsetInfoRepository
    {
        private readonly MysqlContext _context;

        public UsetInfoRepository(MysqlContext context)
        {
            _context = context;
        }

        public async Task<int> AddUserInfoAsync(UserInfoEntity userinfo)
        {
            _context.UserInfos.Add(userinfo);
            return await _context.SaveChangesAsync();
        }

        public async Task<int> DeleteUserInfoAsync(int id)
        {
            var todo = await _context.UserInfos.FirstOrDefaultAsync(item => item.UId == id);
            if (todo == null)
            {
                return 0;
            }
            else
            {
                _context.UserInfos.Remove(todo);
                return await _context.SaveChangesAsync();
            }
        }

        public async Task<IEnumerable<UserInfoEntity>> GetAllUserInfoAsync()
        {
            return await _context.UserInfos.ToListAsync();
        }

        public async Task<UserInfoEntity> GetUserInfoAsync(int id, string password)
        {
            return await _context.UserInfos.SingleOrDefaultAsync(item => item.UId == id && item.PassWord == password);
        }

        public async Task<int> GetUserisExistenceAsync(int id)
        {
            return await _context.UserInfos.CountAsync(item => item.UId == id);
        }

        public async Task<int> UpdateUserInfoAsync(UserInfoEntity userinfo)
        {
            _context.UserInfos.Update(userinfo);
            return await _context.SaveChangesAsync();
        }

    }
}
